<template>
	<view class="chat-container">


		<!-- 聊天记录区域 -->
		<scroll-view 
			class="chat-messages" 
			scroll-y="true" 
			:scroll-top="scrollTop" 
			scroll-with-animation="true"
		>
			<view class="message-list">
				<!-- AI欢迎消息 -->
				<view class="message ai-message">
					<view class="message-avatar">
						<view class="ai-avatar">
							<uni-icons type="chat" size="20" color="#fff"></uni-icons>
						</view>
					</view>
					<view class="message-content">
						<view class="message-bubble">
							<text class="message-text">您好！我是您的AI智能助教，有什么可以帮助您的吗？</text>
						</view>
					</view>
				</view>

				<!-- 用户消息和时间分隔器 -->
				<view v-for="(message, index) in chatMessages" :key="`message-${index}`" class="message-wrapper">
					<!-- 时间分隔器（显示在消息上方） -->
					<view v-if="shouldShowTimeDivider(index)" class="time-divider">
						<text class="time-text">{{ message.time }}</text>
					</view>
					
					<!-- 消息内容 -->
					<view class="message" :class="message.type">
						<!-- AI消息：头像在左边 -->
						<view v-if="message.type === 'ai-message'" class="message-avatar">
							<view class="ai-avatar">
								<uni-icons type="chat" size="20" color="#fff"></uni-icons>
							</view>
						</view>
						
						<view class="message-content">
							<view class="message-bubble">
								<!-- 文字消息 -->
								<view v-if="message.content && !message.image" class="text-message-container">
									<text class="message-text">{{ message.content }}</text>
									<!-- 流式输出时显示打字光标 -->
									<text v-if="message.isStreaming" class="typing-cursor">|</text>
								</view>
								<!-- 图片消息 -->
								<view v-if="message.image" class="image-message">
									<image 
										:src="message.image" 
										mode="aspectFit" 
										class="message-image"
										@tap="previewImage(message.image)"
									></image>
									<text v-if="message.content" class="image-caption">{{ message.content }}</text>
								</view>
								<!-- 文字+图片消息 -->
								<view v-if="message.content && message.image" class="mixed-message">
									<text class="message-text">{{ message.content }}</text>
									<image 
										:src="message.image" 
										mode="aspectFit" 
										class="message-image"
										@tap="previewImage(message.image)"
									></image>
								</view>
							</view>
						</view>
						
						<!-- 用户消息：头像在右边 -->
						<view v-if="message.type === 'user-message'" class="message-avatar user-avatar">
							<view class="user-avatar-circle">
								<uni-icons type="person" size="16" color="#fff"></uni-icons>
							</view>
						</view>
					</view>
				</view>

				<!-- 正在输入提示（仅在非流式输出时显示） -->
				<view v-if="isTyping && !hasStreamingMessage" class="message ai-message">
					<view class="message-avatar">
						<view class="ai-avatar">
							<uni-icons type="chat" size="20" color="#fff"></uni-icons>
						</view>
					</view>
					<view class="message-content">
						<view class="message-bubble typing-bubble">
							<view class="typing-dots">
								<view class="dot"></view>
								<view class="dot"></view>
								<view class="dot"></view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 输入区域 -->
		<view class="chat-input-area">
			<view class="input-container">
				<view class="input-actions-left">
					<uni-icons 
						type="camera" 
						size="24" 
						color="#666" 
						@tap="selectImage"
					></uni-icons>
				</view>
				<view class="input-wrapper">
					<input 
						class="message-input" 
						v-model="inputMessage" 
						placeholder="请输入您的问题..." 
						:disabled="isTyping"
						@confirm="sendMessage"
					/>
				</view>
				<view class="input-actions-right">
					<view 
						class="send-btn" 
						:class="{ 'active': inputMessage.trim() }"
						@tap="sendMessage"
					>
						<text class="send-text">{{ inputMessage.trim() ? '发送' : '图片' }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, nextTick, watch, computed } from 'vue';
	// 导入AI API服务
	import aiApiService from '../../utils/ai-api.js';

	const inputMessage = ref('');
	const chatMessages = ref([]);
	const isTyping = ref(false);
	const isSending = ref(false); // 是否正在发送消息
	const scrollTop = ref(0);
	const aiServiceStatus = ref(null); // AI服务状态

	// 检查是否有正在流式输出的消息
	const hasStreamingMessage = computed(() => {
		return chatMessages.value.some(message => message.isStreaming);
	});

	// 获取当前时间
	const getCurrentTime = () => {
		const now = new Date();
		return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
	};

	// 选择图片
	const selectImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0];
				sendImageMessage(tempFilePath);
			},
			fail: (err) => {
				console.log('选择图片失败:', err);
			}
		});
	};

	// 发送图片消息
	const sendImageMessage = async (imagePath: string, caption: string = '') => {
		const userMessage = {
			type: 'user-message',
			content: caption,
			image: imagePath,
			time: getCurrentTime()
		};

		chatMessages.value.push(userMessage);
		
		// 滚动到底部
		scrollToBottom();

		// 发送图片消息给AI（暂时只发送文字说明）
		isTyping.value = true;
		try {
			const imageMessage = caption || '我发送了一张图片';
			const response = await aiApiService.sendMessage(imageMessage);
			
			if (response.success) {
				chatMessages.value.push({
					type: 'ai-message',
					content: response.content,
					time: getCurrentTime()
				});
			} else {
				throw new Error(response.error || 'AI服务异常');
			}
		} catch (error) {
			console.error('AI图片消息处理失败:', error);
			chatMessages.value.push({
				type: 'ai-message',
				content: '抱歉，我现在无法处理图片消息，但我看到您发送了一张图片。请用文字描述您需要帮助的内容。',
				time: getCurrentTime()
			});
		} finally {
			isTyping.value = false;
			// AI回复后滚动到底部
			scrollToBottom();
		}
	};

	// 预览图片
	const previewImage = (imagePath: string) => {
		uni.previewImage({
			urls: [imagePath],
			current: imagePath
		});
	};

	// 发送消息
	const sendMessage = async () => {
		if (!inputMessage.value.trim() || isTyping.value || isSending.value) return;
		
		// 设置发送状态，防止重复发送
		isSending.value = true;

		const userMessage = {
			type: 'user-message',
			content: inputMessage.value,
			time: getCurrentTime()
		};

		chatMessages.value.push(userMessage);
		const message = inputMessage.value;
		inputMessage.value = '';
		
		// 滚动到底部
		scrollToBottom();

		// 发送消息给AI服务（使用流式回答）
		// 注意：流式输出时不设置isTyping，因为我们直接添加消息占位符
		
		// 先添加一个空的AI消息占位符
		const aiMessageIndex = chatMessages.value.length;
		chatMessages.value.push({
			type: 'ai-message',
			content: '', // 开始时为空，将逐步填充
			time: getCurrentTime(),
			isStreaming: true // 标记为正在流式输出
		});
		
		try {
			console.log('🌊 [AI聊天] 发送流式消息给AI:', message);
			console.log('🔗 [AI聊天] 使用AI API服务:', aiApiService);
			
			// 使用流式发送方法
			await aiApiService.sendMessageStream(message, (partialContent, isComplete) => {
				// 更新AI消息的内容
				if (chatMessages.value[aiMessageIndex]) {
					chatMessages.value[aiMessageIndex].content = partialContent;
					chatMessages.value[aiMessageIndex].isStreaming = !isComplete;
					
					// 每次更新后滚动到底部
					setTimeout(() => scrollToBottom(), 50);
				}
			});
			
			console.log('🎉 [AI聊天] 流式回答完成');
			
		} catch (error) {
			console.error('AI流式消息发送失败:', error);
			// 更新AI消息为错误内容
			if (chatMessages.value[aiMessageIndex]) {
				chatMessages.value[aiMessageIndex].content = `抱歉，我暂时无法回复您的消息。${getErrorMessage(error)}`;
				chatMessages.value[aiMessageIndex].isStreaming = false;
			}
		} finally {
			// 重置发送状态
			isSending.value = false;
			// 最终滚动到底部
			setTimeout(() => scrollToBottom(), 100);
		}
	};

	// 获取友好的错误信息
	const getErrorMessage = (error) => {
		const errorMessage = error.message || error.toString();
		
		if (errorMessage.includes('timeout') || errorMessage.includes('连接超时')) {
			return 'AI服务连接超时，请检查网络连接。';
		}
		
		if (errorMessage.includes('网络请求失败') || errorMessage.includes('连接失败')) {
			return 'AI服务连接失败，请确保后端服务已启动。';
		}
		
		if (errorMessage.includes('500')) {
			return 'AI服务内部错误，请稍后重试。';
		}
		
		return '请稍后重试或联系技术支持。';
	};

	// 检查AI服务状态
	const checkAIServiceStatus = async () => {
		try {
			const healthCheck = await aiApiService.checkHealth();
			aiServiceStatus.value = healthCheck;
			
			if (!healthCheck.success) {
				console.warn('AI服务不可用:', healthCheck.error);
				// 显示服务不可用的提示
				uni.showToast({
					title: 'AI服务暂时不可用',
					icon: 'none',
					duration: 3000
				});
			} else {
				console.log('AI服务运行正常:', healthCheck.service);
			}
		} catch (error) {
			console.error('AI服务状态检查失败:', error);
			aiServiceStatus.value = { success: false, error: error.message };
		}
	};

	// 滚动到底部
	const scrollToBottom = () => {
		// 立即设置一个很大的值来滚动到底部
		scrollTop.value = 999999;
		
		// 使用nextTick确保DOM更新后再滚动
		nextTick(() => {
			// 再次设置确保滚动生效
			scrollTop.value = 999999;
		});
		
		// 使用setTimeout作为备用方案，确保滚动生效
		setTimeout(() => {
			scrollTop.value = 999999;
		}, 100);
	};

	// 清空聊天记录
	const clearChat = () => {
		uni.showModal({
			title: '清空聊天',
			content: '确定要清空所有聊天记录吗？',
			success: (res) => {
				if (res.confirm) {
					chatMessages.value = [];
				}
			}
		});
	};

	// 判断是否应该显示时间分隔器
	const shouldShowTimeDivider = (index: number) => {
		if (index === 0) return true; // 第一条消息总是显示时间
		
		const currentMessage = chatMessages.value[index];
		const previousMessage = chatMessages.value[index - 1];
		
		if (!currentMessage || !previousMessage) return false;
		
		// 解析时间字符串 (格式: "HH:MM")
		const currentTime = parseTimeString(currentMessage.time);
		const previousTime = parseTimeString(previousMessage.time);
		
		if (!currentTime || !previousTime) return false;
		
		// 计算时间差（分钟）
		const timeDiff = Math.abs(currentTime - previousTime);
		
		// 如果时间差超过2分钟，显示时间分隔器
		return timeDiff > 2;
	};
	
	// 解析时间字符串为分钟数
	const parseTimeString = (timeStr: string) => {
		const parts = timeStr.split(':');
		if (parts.length !== 2) return null;
		
		const hours = parseInt(parts[0]);
		const minutes = parseInt(parts[1]);
		
		if (isNaN(hours) || isNaN(minutes)) return null;
		
		return hours * 60 + minutes;
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 监听聊天消息变化，自动滚动到底部
	watch(chatMessages, () => {
		// 每次消息变化都滚动到底部
		scrollToBottom();
	}, { deep: true, immediate: true });

	// 监听输入状态变化，确保在AI输入时也滚动
	watch(isTyping, (newValue) => {
		if (newValue) {
			// AI开始输入时滚动
			scrollToBottom();
		}
	});

	onMounted(() => {
		// 页面加载完成后滚动到底部
		nextTick(() => {
			scrollToBottom();
		});
		
		// 检查AI服务状态
		checkAIServiceStatus();
	});
</script>

<style>
	page {
		background-color: #ededed;
	}

	.chat-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}



	/* 聊天记录区域 */
	.chat-messages {
		flex: 1;
		padding: 20rpx;
		padding-bottom: 120rpx;
	}

	.message-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.message-wrapper {
		display: flex;
		flex-direction: column;
	}

	.message {
		display: flex;
		align-items: flex-start;
		gap: 16rpx;
	}

	.message.user-message {
		flex-direction: row;
	}

	.message.user-message .message-content {
		order: 1;
	}

	.message.user-message .message-avatar {
		order: 2;
	}

	.message-avatar {
		flex-shrink: 0;
	}

	.ai-avatar {
		width: 80rpx;
		height: 80rpx;
		background: #95ec69;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.user-avatar {
		order: 1;
	}

	.user-avatar-circle {
		width: 80rpx;
		height: 80rpx;
		background: #95ec69;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.message-content {
		flex: 1;
		max-width: 75%;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.message.user-message .message-content {
		align-items: flex-end;
	}

	.message-bubble {
		background: #ffffff;
		padding: 20rpx 24rpx;
		border-radius: 8rpx;
		margin-bottom: 8rpx;
		position: relative;
		display: inline-block;
		max-width: 100%;
		word-wrap: break-word;
		word-break: break-all;
	}

	.message-bubble::before {
		content: '';
		position: absolute;
		top: 20rpx;
		left: -8rpx;
		width: 0;
		height: 0;
		border: 8rpx solid transparent;
		border-right-color: #ffffff;
	}

	.user-message .message-bubble {
		background: #95ec69;
		color: #000000;
	}

	.user-message .message-bubble::before {
		left: auto;
		right: -8rpx;
		border-right-color: transparent;
		border-left-color: #95ec69;
	}

	/* 用户消息气泡小三角位置调整 */
	.message.user-message .message-bubble::before {
		left: auto;
		right: -8rpx;
		border-right-color: transparent;
		border-left-color: #95ec69;
	}

	.message-text {
		font-size: 32rpx;
		line-height: 1.5;
		color: #333;
		white-space: pre-wrap;
		word-wrap: break-word;
		word-break: break-all;
	}

	.user-message .message-text {
		color: #000000;
	}

	/* 流式输出容器 */
	.text-message-container {
		display: flex;
		align-items: flex-end;
		flex-wrap: wrap;
	}

	/* 打字光标动画 */
	.typing-cursor {
		color: #007aff;
		font-size: 32rpx;
		margin-left: 4rpx;
		animation: blink 1s infinite;
		font-weight: bold;
	}

	@keyframes blink {
		0%, 50% { opacity: 1; }
		51%, 100% { opacity: 0; }
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
		display: block;
		margin-top: 8rpx;
		text-align: center;
	}

	/* 时间分隔器样式 */
	.time-divider {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 20rpx 0;
	}

	.time-text {
		background: #ededed;
		padding: 8rpx 16rpx;
		border-radius: 12rpx;
		font-size: 24rpx;
		color: #999;
	}

	/* 正在输入动画 */
	.typing-bubble {
		background: #f0f0f0;
		padding: 16rpx 20rpx;
	}

	.typing-dots {
		display: flex;
		gap: 8rpx;
		align-items: center;
	}

	.dot {
		width: 8rpx;
		height: 8rpx;
		background: #999;
		border-radius: 50%;
		animation: typing 1.4s infinite ease-in-out;
	}

	.dot:nth-child(1) { animation-delay: -0.32s; }
	.dot:nth-child(2) { animation-delay: -0.16s; }

	@keyframes typing {
		0%, 80%, 100% {
			transform: scale(0.8);
			opacity: 0.5;
		}
		40% {
			transform: scale(1);
			opacity: 1;
		}
	}

	/* 输入区域 */
	.chat-input-area {
		background: #f5f5f5;
		padding: 20rpx 30rpx;
		border-top: 1px solid #d9d9d9;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}

	.input-container {
		display: flex;
		align-items: center;
		gap: 20rpx;
		background: #ffffff;
		border-radius: 8rpx;
		padding: 16rpx 20rpx;
		border: 1px solid #d9d9d9;
	}

	.input-wrapper {
		flex: 1;
	}

	.message-input {
		width: 100%;
		font-size: 32rpx;
		color: #333;
		background: transparent;
		border: none;
		outline: none;
		padding: 8rpx 0;
	}

	.input-actions-left {
		padding: 8rpx;
	}

	.input-actions-right {
		padding: 8rpx;
	}

	.send-btn {
		background: #f0f0f0;
		border-radius: 8rpx;
		padding: 16rpx 24rpx;
		min-width: 80rpx;
		text-align: center;
		transition: all 0.3s ease;
	}

	.send-btn.active {
		background: #07c160;
	}

	.send-text {
		font-size: 28rpx;
		color: #666;
	}

	.send-btn.active .send-text {
		color: #ffffff;
	}

	/* 图片消息样式 */
	.image-message {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.message-image {
		width: 300rpx;
		height: 300rpx;
		border-radius: 8rpx;
		background: #f0f0f0;
	}

	.image-caption {
		font-size: 28rpx;
		color: #666;
		line-height: 1.4;
	}

	.mixed-message {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.mixed-message .message-image {
		align-self: flex-start;
	}
</style>
